const marked = require('marked')
const xss = require('xss')
const Ac = require('../lib/mongo').Ac
const CommentModel = require('./comments')
const EpModel = require('./ep')

// 给 post 添加留言数 commentsCount
Ac.plugin('addCommentsCount', {
  afterFind: (posts) => {
    return Promise.all(posts.map((post) => {
      return CommentModel.getCommentsCount(post._id).then((commentsCount) => {
        post.commentsCount = commentsCount
        return post
      })
    }))
  },
  afterFindOne: (post) => {
    if (post) {
      return CommentModel.getCommentsCount(post._id).then((count) => {
        post.commentsCount = count
        return post
      })
    }
    return post
  }
})

// 给 post 添加剧集数  epsCount
Ac.plugin('addEpsCount', {
  afterFind: (posts) => {
    return Promise.all(posts.map((post) => {
      return EpModel.getEpsCount(post._id).then((count) => {
        post.epsCount = count
        return post
      })
    }))
  },
  afterFindOne: (post) => {
    if (post) {
      return EpModel.getEpsCount(post._id).then((count) => {
        post.epsCount = count
        return post
      })
    }
    return post
  }
})

// 将 post 的 content 从 markdown 转换成 html
Ac.plugin('contentToHtml', {
  afterFind: (posts) => {
    return posts.map((post) => {
      post.content = marked(xss(post.content))
      return post
    })
  },
  afterFindOne: (post) => {
    if (post) {
      post.content = marked(xss(post.content))
    }
    return post
  }
})

module.exports = {
  // 创建
  create: function create (post) {
    return Ac.create(post).exec()
  },

  // 通过 id 给 pv 加 1
  incPv: function incPv (postId) {
    return Ac
      .update({ _id: postId }, { $inc: { pv: 1 } })
      .exec()
  },

  // 通过 id 获取详情
  getPostById: function getPostById (postId) {
    return Ac
      .findOne({ _id: postId })
      .populate({ path: 'author', model: 'User' })
      .addCreatedAt()
      .addCommentsCount()
      .addEpsCount()
      .contentToHtml()
      .exec()
  },

  // 按创建时间降序获取所有
  getPosts: function getPosts (author, limit, skip) {
    const query = {}
    if (author) {
      query.author = author
    }
    return Ac
      .find(query)
      .limit(limit)
      .skip(skip)
      .populate({ path: 'author', model: 'User' })
      .sort({ _id: -1 })
      .addCreatedAt()
      .addCommentsCount()
      .addEpsCount()
      .contentToHtml()
      .exec()
  },

  // 通过 id 获取一个原生详情（编辑文章）
  getRawAcById: function getRawAcById (acId) {
    return Ac
      .findOne({ _id: acId })
      .populate({ path: 'author', model: 'User' })
      .exec()
  },

  // 通过 id 更新
  updateAcById: function updateAcById (acId, data) {
    return Ac.update({ _id: acId }, { $set: data }).exec()
  },

  // 通过 id 删除
  delAcById: function delAcById (acId, typeId) {
    return Ac.deleteOne({ _id: acId })
      .exec()
      .then(function (res) {
        // 删除后，再删除该ID下所有留言
        if (res.result.ok && res.result.n > 0) {
          return CommentModel.delCommentsByPostId(acId, typeId)
        }
      })
  }
}
